package com.orhanobut.logger;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

/**
 * LogCat implementation for {@link LogStrategy}
 *
 * This simply prints out all logs to HiLog by using standard {@link HiLog} class.
 */
public class HiLogStrategy implements LogStrategy {

  static final String DEFAULT_TAG = "NO_TAG";
  private static final int MAX_LOG_LENGTH = 4000;

  private final ThreadLocal<HiLogLabel> currentLabel = new ThreadLocal<>();
  private final ThreadLocal<String> currentTag = new ThreadLocal<>();

  @Override public void log(int priority, @Nullable String tag, @NonNull String message) {
      Utils.checkNotNull(message);

    if (tag == null) {
      tag = DEFAULT_TAG;
    }

    HiLogLabel label = getHiLogLabel(tag);
    if (message.length() < MAX_LOG_LENGTH) {
      if (priority == HiLog.FATAL) {
        HiLog.fatal(label,message);
      } else  if (priority == HiLog.INFO){
        HiLog.info(label, message);
      }else if (priority == HiLog.WARN){
        HiLog.warn(label, message);
      }else if (priority == HiLog.ERROR){
        HiLog.error(label, message);
      }else if (priority == HiLog.DEBUG){
        HiLog.debug(label, message);
      }
      return;
    }

    // Split by line, then ensure each line can fit into Log's maximum length.
    for (int i = 0, length = message.length(); i < length; i++) {
      int newline = message.indexOf('\n', i);
      newline = newline != -1 ? newline : length;
      do {
        int end = Math.min(newline, i + MAX_LOG_LENGTH);
        String part = message.substring(i, end);
        if (priority == HiLog.FATAL) {
          HiLog.fatal(label,part);
        }else  if (priority == HiLog.INFO){
          HiLog.info(label, message);
        }else if (priority == HiLog.WARN){
          HiLog.warn(label, message);
        }else if (priority == HiLog.ERROR){
          HiLog.error(label, message);
        }else if (priority == HiLog.DEBUG){
          HiLog.debug(label, message);
        }
        i = end;
      } while (i < newline);
    }
  }

  private HiLogLabel getHiLogLabel(String tag) {
    HiLogLabel label;
    if (tag.equals(currentTag.get())) {
      label = currentLabel.get();
//        HiLog.error(label, "----get label----");
    } else {
      label = new HiLogLabel(HiLog.DEBUG,0,tag);
//        HiLog.error(label, "----new label----");
      currentLabel.set(label);
      currentTag.set(tag);
    }
    return label;
  }
}

